//
//  WYComposeViewController.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/21.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit
import SVProgressHUD

class WYComposeViewController: UIViewController {
    //MARK: -- 懒加载控件
    private lazy var titleLabel: UILabel = {
        
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        
        //获取用户名 
        if let name = WYUserAccountViewModel.sharedUserAccount.userAccount?.name {
        
            let title = "发微博\n\(name)"
            let attributeStr = NSMutableAttributedString(string: title)
            //获取名字范围
            let range = (title as NSString).rangeOfString(name)
            attributeStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(),NSFontAttributeName: UIFont.systemFontOfSize(12)],range: range)
            label.attributedText = attributeStr
            
        } else {
        
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
        
        
    }()
    //右侧按钮(发送按钮)
    private lazy var rightButton: UIButton = {
    
        let button = UIButton()
        
        //添加点击事件
        button.addTarget(self, action: "sendMessage", forControlEvents: .TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_Highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
       
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        //因为 button 被UibarButtonitem 控制 这里禁用没有 
//        button.enabled = false
        button.size = CGSize(width: 45, height: 30)
        
        
        return button
    }()
    
    //添加自定义textView
    private lazy var textView: WYComposeTextView = {
    
        let view = WYComposeTextView()
        view.placeHolder = "别低头,绿帽子会掉~~~"
        view.font = UIFont.systemFontOfSize(15)
        
        view.delegate = self
        //垂直方向开启弹簧效果
        view.alwaysBounceVertical = true
        return view
        
    }()
    
    //自定义 toolBar
    private lazy var toolBar: WYComposeToolBar = {
    
        let view = WYComposeToolBar(frame: CGRectZero)
        
        return view
    }()
    //添加图片
    private lazy var pictureView: WYComposePictureView = {
        
        let pictureView = WYComposePictureView()
        return pictureView
    
    }()
    //表情键盘
    private lazy var keyBoard: WYEmoticonKeyBoard = {
    
        let view = WYEmoticonKeyBoard()
        //设置大小
        view.size = CGSize(width: self.textView.width, height: 216)
        
        return view
    
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.redColor()
        setUpUI()
    }
    
    private func setUpUI() {
    
        //监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //监听表情按钮的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticon:", name: DidSelectedEmotionbuttonNotification, object: nil)
        //监听删除按钮改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didButtonDeleteTextViewText", name: DidBUttonDeleteTextViewtextNotification, object: nil)
        setupNav()
        //添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        //j将图片 view 添加在 textView 上
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.width.equalTo(30)
            
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(textView).offset(10)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
            
        }
        //设置闭包
        toolBar.selectedToolBarButtonClouse = { [weak self] (type: WYComposeToolBarButtonType) in
            
          switch type {
            
                case .Picture:
                    print("图片")
                    self?.didSelectedPicker()
                case .Mention:
                    print("@")
                case .Trend:
                    print("话题")
                case .EmoTicon:
                    print("表情")
                    self!.didSelectecEmoticon()
                case .Add:
                    print("加号")
            
            }
        }
        
        //选择闭包
        pictureView.didSelectedAddClouse = {[weak self] in
            //打开图片选择器
            self?.didSelectedPicker()

        }
    }
    /*!
    设置头部文件
    */
    private func setupNav() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target:  self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleLabel
    }
    
    //处理点击事件
    @objc private func cancelAction() {
        //?
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    /*!
    发送微博的点击事件
    */
    @objc private func sendMessage() {
    
//        let accessToken = WYUserAccountViewModel.sharedUserAccount.accessToken!
//        let text = textView.text!
//        SVProgressHUD.show()
//        WYNetWorkingTools.sharedTools.update(accessToken, status: text) { (response, error) -> () in
//            if error != nil {
//            
//                print(error)
//                SVProgressHUD.showErrorWithStatus("发送失败")
//                return
//            }
//            SVProgressHUD.showInfoWithStatus("发送成功")
//        }
        
        //带图片微博上传接口
        if pictureView.images.count > 0 {
        
            let image = pictureView.images.first!
            let accessToken = WYUserAccountViewModel.sharedUserAccount.accessToken!
            let text = textView.text!
            SVProgressHUD.show()
            
            WYNetWorkingTools.sharedTools.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
                if error != nil {
                
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                } else {
                
                    //发送成功
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                   self.presentViewController(WYMainViewController(), animated: true, completion: nil)
                    
                }
            })
        } else {
        
            //发送微博接口
            let accessToken = WYUserAccountViewModel.sharedUserAccount.accessToken
            let text = textView.text!
            SVProgressHUD.show()
            
            WYNetWorkingTools.sharedTools.update(accessToken!, status: text, callBack: { (response, error) -> () in
                if error != nil {
                
                    print("发送失败")
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                } else {
                
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                }
            })
            
        }
        
    }
    
    @objc private func keyboardChangeFrame(noti: NSNotification) {
    
        //获取屏幕的 frame
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //跟新约束  跟新约束 来回移动
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - Screenheight)
        }
        //自行动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
  
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension WYComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //根据内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    //让view 跟随键盘移动
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
//        loadView()
    }
    
}

//处理 toolbar 按钮点击的逻辑
extension WYComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //表情键盘的处理
    func didSelectecEmoticon() {
        
        //显示表情键盘 或者 系统键盘 inputView 会出现在键盘的上方
        //inputView 会和键盘交替出现 
        if textView.inputView == nil {
        
            //设置表情键盘 
            textView.inputView = keyBoard
            //
            toolBar.showEmoticonIcon(true)
        } else {
            //设置为系统键盘
            textView.inputView = nil
            toolBar.showEmoticonIcon(false)
        }
        //获取第一响应者
        textView.becomeFirstResponder()
        //帅新 inputView
        textView.reloadInputViews()
        
    }
    
    
    func didSelectedPicker() {
        print("\(self.pictureView.images.count)======")

        if self.pictureView.images.count >= 9 {
        print(self.pictureView.images.count)
            SVProgressHUD.showInfoWithStatus("亲,最多只能加九张图片")
            
        } else {
            
            let imagePicekerCon = UIImagePickerController()
            //设置代理
            imagePicekerCon.delegate = self
            //判断是否支持这个来源类型
            if UIImagePickerController.isSourceTypeAvailable(.Camera) {
                imagePicekerCon.sourceType = .Camera
                print("支持")
            } else {
                
                imagePicekerCon.sourceType = .PhotoLibrary
                print("不支持相机,使用的图库")
            }
            //判断是否支持前置 后置摄像头
            if UIImagePickerController.isCameraDeviceAvailable(.Front) {
                
                print("支持前置摄像头")
            } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
                
                print("支持后摄像头")
            } else {
                
                print("前后摄像头不支持")
            }
            //允许用户编辑
            //        imagePicekerCon.allowsEditing = true
            presentViewController(imagePicekerCon, animated: true, completion: nil)

            
        }

            }
    //获取选中的图片 如果实现了协议就不会自己调用 dismissViewControllerAnimation
    //选择图片后调用的方法
    func  imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        
//        pictureView.addImage(image)
        //给图片大小 和 内容
        let scaleIamge = image.scaleImageWithScaleWidth(200, image: image)
        print(scaleIamge)
        //添加压缩后图片
        pictureView.addImage(scaleIamge)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: -- 监听删除按钮的通知
    @objc private func didButtonDeleteTextViewText() {
        //删除内容
        textView.deleteBackward()
    }
    
    //#MARK: -- 监听表情点击的通知
    @objc private func didSelectedEmoticon(noti: NSNotification) {
        
        let emoticon = noti.object as! WYEmoticon
        print(emoticon.type)
        textView.insertEmoticon(emoticon)
//        if emoticon.type == "0" {
        
        //移到 WYComposeTextView+Extension 中
        
////            let chs = emoticon.chs!
////            textView.insertText(chs)
//            //通过图片创建富文本
//            //记录上一次的富文本
//            let originaAttributeStr = NSMutableAttributedString(attributedString: textView.attributedText)
//            //1 获取图片
//            let image = UIImage(named: emoticon.path!)
//            //2 通过图片转化为文本附件(NStextAttachment)
//            let attachment = NSTextAttachment()
//            attachment.image = image
//            //获取行高 指定图片大小
//            let fontHeight = textView.font!.lineHeight
//            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//            //3 通过 NStextAttachment 创建富文本
//            let attributtedStr = NSAttributedString(attachment: attachment)
////            originaAttributeStr.appendAttributedString(attributtedStr)
//            //获取 textView 的选中范围
//            var range = textView.selectedRange
//            //将选中的范围替换为想要的恩富文本
//            originaAttributeStr.replaceCharactersInRange(range, withAttributedString: attributtedStr)
//            
//            //5指定富文本值大小
//            originaAttributeStr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, originaAttributeStr.length))
//            //4 给我们的 textView 设置富文本(attributtedtext)
//            textView.attributedText = originaAttributeStr
//            //  每次点击让其光标位置加1, 设置其选中范围的长度为0
//            range.location += 1; range.length = 0
//            //根据选中的范围设置贯标的位置
//            textView.selectedRange = range
//        } else {
//        
//            let emoji = (emoticon.code! as NSString).emoji()
//            textView.insertText(emoji)
//        }
//    }
  }

}